package top.kikt.book.core.handlers.common

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import top.kikt.book.core.base.IBookHandler
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty
import top.kikt.book.util.resolveBySrcUrl
import java.nio.charset.Charset

interface CommonBookHandler : IBookHandler {

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        return Handler.parseBookMeta(document, url)
    }

    override fun forceCharset(): Charset? = Charset.forName("gbk")

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        return Handler.parseChapter(chapterMetaEntity, this)
    }


    companion object Handler {
        fun parseBookMeta(document: Document, url: String): BookMetaEntity {
            // 获取书籍信息
            val name = document.metaContentWithProperty("og:novel:book_name")
            val author = document.metaContentWithProperty("og:novel:author")
            val coverUrl = document.metaContentWithProperty("og:image").resolveBySrcUrl(url)

            return BookMetaEntity(name, url, url, author, coverUrl)
        }

        fun parseChapter(chapterMetaEntity: ChapterMetaEntity, bookHandler: IBookHandler): ChapterEntity {
            val response = bookHandler.get(chapterMetaEntity.url)
            val stream = response.body?.byteStream() ?: throw IllegalStateException("Can't get chapter content")
            val doc = Jsoup.parse(stream, bookHandler.charset.name(), chapterMetaEntity.url)
            val content = doc.select("#content").bookText() ?: throw IllegalStateException(
                "Happen exception in CommonHandler, maybe need recreate parseChapter method in ${bookHandler.javaClass.name}"
            )
            return chapterMetaEntity.toChapterMetaEntity(content)
        }
    }
}